import React, { forwardRef, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import {
    Spin,
    Steps,
    Checkbox,
    Button,
    Select,
    message,
    Form,
    Row,
    Col,
    Input,
    Radio,
    Switch,
    Popover,
    Icon,
    Modal
} from 'antd';
import { isEqual, defaults } from 'lodash';

import { withRoutePage } from '@/utils/enhanceUtils';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { isSuccess } from '@/utils/request';
import { BottomAction } from '@/components';
import { SearchInput } from '@/components/UserForm';
import OrganizationSelect from '@/components/OrganizationSelect';
import { makeArray, arrayToString } from '@/pages/SalaryManage/utils';
import AuthComponent from '@/utils/auth/AuthComponent';

import {
    queryParameterInfo,
    queryDictList,
    onSaveParameterSetting,
    onSalarySetReset
} from '@/services/salaryManage/salaryCalculate';
import {
    goToProcessDetail,
    goToSalaryPaySettingLog,
    goToProcessApply
} from '@/pages/SalaryManage/utils/pageNavigateUtil';
import { financeInit, queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import StatusTag from '@/pages/SalaryManage/components/ProcessStatus';
import { PROCESS_TYPE } from '@/pages/SalaryManage/utils/processUtil';
import { DutySelector, useFetchDutyData } from '@/components/OrgSelector';
import { TabMenuRouter, TabContextMenuFilter } from '@/pages/SalaryManage/components/MenuFilterRouter';
import { MENU_AUTH_CODE_MAP } from '@/pages/SalaryManage/SalaryCalculate/TemplateSetting/components/TemplateSettingRouter';

import useHistoryBlock from '@/pages/SalaryManage/hooks/useHistoryBlock';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';
import styles from '../index.less';
import DictSelect from '../components/DictSelect';

const formItemLayout = {
    labelCol: {
        md: { span: 9 },
        xs: { span: 24 },
        sm: { span: 24 }
    },
    wrapperCol: {
        md: { span: 15 },
        xs: { span: 24 },
        sm: { span: 24 }
    }
};
const { Step } = Steps;
const getFormSettingList = form => [
    {
        id: 'itemChecked',
        showName: '开启细项复核',
        children: [
            {
                id: 'itemKpiDutyCode',
                showName: '绩效系数',
                fixed: true
            },
            {
                id: 'itemFiveDutyCode',
                showName: '险金',
                fixed: true
            },
            {
                id: 'itemTaxDutyCode',
                showName: '个人所得税',
                fixed: true
            }
        ],
        isSecond: true,
        wrapName: 'paramDTOS',
        position: 2
    },
    {
        id: 'hrChecked',
        showName: <React.Fragment>开启HR复核人员</React.Fragment>,
        children: [
            {
                id: 'hrDutyCode',
                showName: 'HR初审人员'
            },
            {
                id: 'hrRecheckDutyCode',
                showName: 'HR复审人员',
                allowClear: true,
                rules: [
                    {
                        validator: (rule, value, callback) => {
                            const formValue = form.getFieldsValue();
                            if (formValue.hrFinalCheckDutyCode && !formValue.hrRecheckDutyCode) {
                                callback(new Error());
                            } else {
                                callback();
                            }
                        },
                        message: '选择了HR终审人员必须选择HR复审人员'
                    }
                ]
            },
            {
                id: 'hrFinalCheckDutyCode',
                showName: 'HR终审人员',
                allowClear: true,
                rules: [],
                onChange: () => {
                    setTimeout(() => {
                        form.validateFields(['hrRecheckDutyCode']);
                    }, 0);
                }
            }
        ],
        position: 3
    },
    {
        id: 'financeChecked',
        showName: <React.Fragment>开启财务复核</React.Fragment>,
        children: [
            {
                id: 'financeDutyCode',
                showName: '财务初审人员'
            },
            {
                id: 'financeRecheckDutyCode',
                showName: '财务复审人员',
                allowClear: true,
                rules: []
            }
        ],
        position: 4
    }
];
const DICT_NAME = [
    'StaffCheckTypeOptions',
    'StaffTriggerPayrollOptions',
    'staffWarnModeOptions',
    'StaffTriggerNextOptions',
    'flowTypeOptions'
];

const ThingsRadioSelect = forwardRef(({ value, onChange, disabled }) => (
    <Radio.Group onChange={onChange} value={value} disabled={disabled}>
        <Radio value={1}>手动触发</Radio>
        <Radio value={2} disabled>
            <span style={{ marginRight: '8px' }}>自动触发</span>
            <Popover content={<span>上个节点完成后自动触发该节点</span>}>
                <Icon type="question-circle" />
            </Popover>
        </Radio>
    </Radio.Group>
));

// 下一步按钮
const NextButton = ({ next, formValueChanged, editData, children }) => {
    const processStatus = editData?.processStatus || null;
    const nextAble = !!editData?.nextAble;
    // 状态为已生效时，则根据表单是否修改过来标志是否可用
    const disabled = processStatus === 3 ? !formValueChanged : !nextAble;
    return (
        <Button type="primary" onClick={next} disabled={disabled}>
            {children}
        </Button>
    );
};

// const DUTY_CACHE_KEY = 'dutyCache1';
// 发放流程多选字段
const multipleStaffKey = ['staffPushPayrollDutyCode', 'workflowDutyCode', 'grantApplyDutyCode', 'payDutyCode'];

const SalaryTemplate = React.memo(({ selectOrganizationCode, form, formValueChanged }) => {
    const { getFieldDecorator, getFieldValue, validateFieldsAndScroll } = form;
    const [pageLoading, setPageLoading] = useState(false);
    const [editData, setEditData] = useState({});
    const [reviewSettingList, setReviewSettingList] = useState([]);
    const [dictList, setDictList] = useState([]);
    const [stepList, setStepList] = useState([]);
    const [resetVisible, setResetVisible] = useState(false);
    const { data: dutyData = [] } = useFetchDutyData();

    const onSetReviewSettingList = (itemEnabled, data) => {
        const formSettingList = getFormSettingList(form);
        const newArr = formSettingList.slice();
        newArr[0] = {
            ...formSettingList[0],
            children: [...data, ...formSettingList[0].children],
            hidden: !itemEnabled
        };
        setReviewSettingList(newArr);
    };
    const onSetSalaryEnsure = (currentCondition, checked) => {
        const noArr = [6, 4, 9]; // 当前条件值对应的索引
        const newStepList = stepList.slice();
        noArr.forEach(i => {
            newStepList[i].enable = false;
            newStepList[i].hidden = true;
        });
        if (
            (typeof checked === 'boolean' && checked) ||
            (typeof checked !== 'boolean' && getFieldValue('staffChecked'))
        ) {
            if (currentCondition) {
                newStepList[noArr[currentCondition - 1]].enable = true;
                newStepList[noArr[currentCondition - 1]].hidden = false;
            } else {
                newStepList[6].enable = true;
                newStepList[6].hidden = true;
            }
            setStepList(newStepList);
        }
    };
    const onChangeStepList = (checked, position) => {
        if (stepList.length) {
            const newStepList = stepList.slice();
            if (position) {
                newStepList[position - 1].enable = checked;
                newStepList[position - 1].hidden = !checked;
                setStepList(newStepList);
            } else {
                // 1-6 2-4 3-8
                const currentCondition = getFieldValue('staffTriggerPayroll');
                onSetSalaryEnsure(currentCondition, checked);
            }
        }
    };
    const onChangeStaffCheckType = staffCheckType => {
        // 非强制确认时，将确认时间清除
        if (staffCheckType !== 1) {
            form.setFieldsValue({ staffTriggerNext: null });
        }
    };
    const onChangeStaffFeedbackEnabled = enabled => {
        // 不允许员工反馈时，清空【接收反馈主管】、【反馈处理组织机构】、【反馈处理组织机构】、
        if (!enabled) {
            form.setFieldsValue({
                staffFeedbackEmployeeCode: undefined,
                staffFeedbackDepartmentCode: undefined,
                staffTips: undefined
            });
        }
    };

    const onChangeStaffConfirmEnabled = enabled => {
        // 不允许员工确认，清空【确认选择】、【系统确认时间】、【对象选择】
        if (!enabled) {
            form.setFieldsValue({
                staffCheckType: undefined,
                staffCheckObject: undefined,
                staffTriggerNext: undefined
            });
        }
    };

    const { mergeTabStore } = useContext(TabStoreContext);

    // 保存
    const onSave = () =>
        new Promise((resolve, reject) => {
            try {
                validateFieldsAndScroll({ scroll: { alignWithTop: true } }, async (err, v) => {
                    if (!err) {
                        setPageLoading(true);
                        const values = arrayToString(v, multipleStaffKey);
                        const paramDTOS = editData.paramDTOS.map(item => ({
                            ...item,
                            checkDutyCode: values.paramDTOS[item.id]
                        }));
                        const params = defaults(
                            {
                                organizationCode: selectOrganizationCode,
                                ...values,
                                paramDTOS,
                                id: editData.id,
                                processVOS: stepList
                            },
                            {
                                staffFeedbackEmployeeCode: null,
                                staffFeedbackDepartmentCode: null,
                                staffTips: null
                            }
                        );
                        if (isEqual(editData, params)) {
                            reject(new Error('表单没有修改，无法进行下一步操作'));
                        }
                        const response = await onSaveParameterSetting(params);
                        if (isSuccess(response)) {
                            resolve(response);
                            message.success('保存成功！');
                        } else {
                            reject(response.msg);
                            message.error(response.msg);
                        }
                        setPageLoading(false);
                    } else {
                        reject(JSON.stringify({ formError: err }));
                    }
                });
            } catch (e) {
                reject(e);
                setPageLoading(false);
            }
        });

    const initData = async () => {
        try {
            setPageLoading(true);
            const { code, data = {}, msg } = await queryParameterInfo(selectOrganizationCode);
            if (code === 10000) {
                setEditData(data);
                setStepList(data.processVOS || []);
                onSetReviewSettingList(data.itemEnabled, data.paramDTOS || []);
            } else {
                message.error(msg);
            }
            setPageLoading(false);
        } catch (e) {
            setPageLoading(false);
            console.log(e);
        }
    };
    const getDict = async () => {
        try {
            const { code, data = {} } = await queryDictList(DICT_NAME.join(','));
            if (code === 10000) {
                setDictList(data);
            }
        } catch (e) {
            console.log(e);
        }
    };

    // 重置
    const reset = async () => {
        try {
            setPageLoading(true);
            const response = await onSalarySetReset(selectOrganizationCode);
            setPageLoading(false);

            form.resetFields();
            if (isSuccess(response)) {
                setResetVisible(false);
                // 刷新界面
                initData();
            } else {
                message.warn(response.msg);
            }
        } catch (e) {
            setResetVisible(false);
            message.error(e);
            setPageLoading(false);
        }
    };

    // 下一步
    const next = async () => {
        try {
            await onSave();
            await goToProcessApply(
                PROCESS_TYPE.SALARY_SET_GRANT_APPLY,
                { apply: '1', organizationCode: selectOrganizationCode },
                '没有找到分类为【财务发放设置流程】的流程，请先配置流程'
            );
            setPageLoading(false);
        } catch (e) {
            try {
                const errorInfo = JSON.parse(e);
                if (!errorInfo.formError) {
                    message.error(e);
                }
            } catch {
                message.error(e.toString());
                console.error(e);
            }
        }
    };

    const handleOrganizationChange = useCallback(
        value => {
            if (selectOrganizationCode !== value) {
                mergeTabStore({
                    selectOrganizationCode: value,
                    countryNameCode: null
                });
            }
        },
        [mergeTabStore, selectOrganizationCode]
    );

    // useEffect(
    //     // 在控件销毁时清除缓存
    //     () => () => {
    //         clearCache(DUTY_CACHE_KEY);
    //     },
    //     []
    // );
    useEffect(() => {
        getDict().then();
    }, []);
    useEffect(() => {
        if (selectOrganizationCode) {
            financeInit(selectOrganizationCode).then(() => {
                initData().then();
            });
        }
    }, [selectOrganizationCode]);

    return (
        <PageHeaderWrapper type="success">
            <TabContextMenuFilter enableDefaultSelect={false}>
                <TabMenuRouter
                    authCodeMap={MENU_AUTH_CODE_MAP}
                    type="templateSetting"
                    extraButton={
                        <div style={{ display: 'flex' }}>
                            <div className={salaryStyle.mr12} style={{ display: 'flex' }}>
                                <OrganizationSelect
                                    isStrictly
                                    isNeedPermission
                                    style={{ width: 220 }}
                                    onChange={handleOrganizationChange}
                                    value={selectOrganizationCode}
                                    allowClear={false}
                                    dropdownMatchSelectWidth
                                />
                            </div>
                            <div>
                                <Button onClick={() => goToSalaryPaySettingLog(selectOrganizationCode)}>
                                    操作日志
                                </Button>
                            </div>
                        </div>
                    }
                >
                    <div className={styles.container}>
                        <Spin spinning={pageLoading}>
                            <div className={styles.salaryContent}>
                                <div className={styles.titleWrap}>
                                    <div className={styles.leftTitleWrap}>
                                        <div className={styles.title}>
                                            流程预览
                                            <StatusTag
                                                templateInfo={{
                                                    processStatus: editData?.processStatus,
                                                    processStatusAble: editData?.processStatusAble
                                                }}
                                            />
                                        </div>
                                    </div>
                                    <div className={styles.rightTitleWrap}>
                                        <Button
                                            type="link"
                                            onClick={() =>
                                                goToProcessDetail({
                                                    processDefinitionId: editData.processDefinitionId,
                                                    processInstanceId: editData.processInstanceId
                                                })
                                            }
                                            className={styles.linkBtn}
                                            disabled={!editData?.approveDetailAble}
                                        >
                                            查看审批详情
                                        </Button>
                                    </div>
                                </div>
                                <div>
                                    <Steps labelPlacement="vertical" className={styles.stepWrap}>
                                        {stepList.map(item => {
                                            if (item.enable && !item.hidden) {
                                                return (
                                                    <Step
                                                        key={item.index}
                                                        title={item.title}
                                                        status={item.fixed ? 'wait' : 'process'}
                                                    />
                                                );
                                            }
                                            return null;
                                        })}
                                    </Steps>
                                </div>
                            </div>
                            <Form {...formItemLayout} hideRequiredMark>
                                <div className={styles.salaryContent}>
                                    <div className={styles.titleWrap}>
                                        <div className={styles.leftTitleWrap}>
                                            <div className={styles.title}>复核设置</div>
                                        </div>
                                    </div>
                                    {reviewSettingList.map(item => (
                                        <div key={item.id} style={item?.hidden ? { display: 'none' } : {}}>
                                            <div className={styles.checkboxWrap}>
                                                {getFieldDecorator(item.id, {
                                                    initialValue: !!editData[item.id],
                                                    valuePropName: 'checked'
                                                })(
                                                    <Checkbox
                                                        onChange={e => {
                                                            onChangeStepList(e.target.checked, item.position);
                                                        }}
                                                        disabled={editData.disable}
                                                    >
                                                        {item.showName}
                                                    </Checkbox>
                                                )}
                                            </div>
                                            <Row gutter={24}>
                                                {item.children.map(child => (
                                                    <Col span={8} key={child.id}>
                                                        <Form.Item label={child.showName}>
                                                            {getFieldDecorator(
                                                                item.isSecond && !child.fixed
                                                                    ? `${item.wrapName}.${child.id}`
                                                                    : child.id,
                                                                {
                                                                    initialValue:
                                                                        item.isSecond && !child.fixed
                                                                            ? child.checkDutyCode || undefined
                                                                            : editData[child.id] || undefined,
                                                                    rules: child.rules || [
                                                                        {
                                                                            required: getFieldValue(item.id),
                                                                            message: `请选择${child.showName}`
                                                                        }
                                                                    ]
                                                                }
                                                            )(
                                                                <DutySelector
                                                                    disabled={
                                                                        editData.disable || !getFieldValue(item.id)
                                                                    }
                                                                    showSearch
                                                                    allowClear
                                                                    onChange={child?.onChange}
                                                                    data={dutyData}
                                                                />
                                                            )}
                                                        </Form.Item>
                                                    </Col>
                                                ))}
                                            </Row>
                                        </div>
                                    ))}
                                </div>
                                <div className={styles.salaryContent}>
                                    <div className={styles.titleWrap}>
                                        <div className={styles.leftTitleWrap}>
                                            <div className={styles.title}>薪资条确认设置</div>
                                        </div>
                                    </div>
                                    <div className={styles.checkboxWrap}>
                                        {getFieldDecorator('staffChecked', {
                                            initialValue: !!editData.staffChecked,
                                            valuePropName: 'checked'
                                        })(
                                            <Checkbox
                                                onChange={e => {
                                                    onChangeStepList(e.target.checked);
                                                }}
                                                disabled={editData.disable}
                                            >
                                                开启薪资条
                                            </Checkbox>
                                        )}
                                    </div>
                                    <Row gutter={24}>
                                        <Col span={8}>
                                            <Form.Item label="触发条件">
                                                {getFieldDecorator('staffTriggerPayroll', {
                                                    initialValue: editData.staffTriggerPayroll || undefined,
                                                    rules: [
                                                        {
                                                            required: getFieldValue('staffChecked'),
                                                            message: '请选择触发条件'
                                                        }
                                                    ]
                                                })(
                                                    <DictSelect
                                                        onChange={onSetSalaryEnsure}
                                                        dictList={dictList}
                                                        dictName="StaffTriggerPayrollOptions"
                                                        disabled={editData.disable || !getFieldValue('staffChecked')}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="下发薪资单">
                                                {getFieldDecorator('staffPushPayrollDutyCode', {
                                                    initialValue: makeArray(editData.staffPushPayrollDutyCode, ','),
                                                    rules: [
                                                        {
                                                            required: getFieldValue('staffChecked'),
                                                            message: '请选择下发薪资单'
                                                        }
                                                    ]
                                                })(
                                                    <DutySelector
                                                        disabled={editData.disable || !getFieldValue('staffChecked')}
                                                        multiple
                                                        showSearch
                                                        max={5}
                                                        data={dutyData}
                                                        modal
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="提醒方式">
                                                {getFieldDecorator('staffWarnMode', {
                                                    initialValue: editData.staffWarnMode || undefined,
                                                    rules: [
                                                        {
                                                            required: getFieldValue('staffChecked'),
                                                            message: '请选择提醒方式'
                                                        }
                                                    ]
                                                })(
                                                    <DictSelect
                                                        dictList={dictList}
                                                        dictName="staffWarnModeOptions"
                                                        disabled={editData.disable || !getFieldValue('staffChecked')}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row gutter={24}>
                                        <Col span={8}>
                                            <Form.Item label="是否要员工确认">
                                                {getFieldDecorator('staffConfirmEnabled', {
                                                    initialValue: !!editData.staffConfirmEnabled || undefined,
                                                    valuePropName: 'checked'
                                                })(
                                                    <Switch
                                                        disabled={editData.disable || !getFieldValue('staffChecked')}
                                                        onChange={onChangeStaffConfirmEnabled}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row gutter={24}>
                                        <Col span={8}>
                                            <Form.Item label="确认选择">
                                                {getFieldDecorator('staffCheckType', {
                                                    initialValue: editData.staffCheckType || undefined,
                                                    rules: [
                                                        {
                                                            required:
                                                                getFieldValue('staffChecked') &&
                                                                getFieldValue('staffConfirmEnabled'),
                                                            message: '请选择确认选择'
                                                        }
                                                    ]
                                                })(
                                                    <DictSelect
                                                        dictList={dictList}
                                                        dictName="StaffCheckTypeOptions"
                                                        disabled={
                                                            editData.disable ||
                                                            !getFieldValue('staffChecked') ||
                                                            !getFieldValue('staffConfirmEnabled')
                                                        }
                                                        onChange={onChangeStaffCheckType}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        {getFieldValue('staffCheckType') === 2 ? (
                                            <Col span={8}>
                                                <Form.Item label="选择对象">
                                                    {getFieldDecorator('staffCheckObject', {
                                                        initialValue: editData.staffCheckObject || 1,
                                                        rules: [
                                                            {
                                                                required:
                                                                    getFieldValue('staffChecked') &&
                                                                    getFieldValue('staffConfirmEnabled'),
                                                                message: '请选择选择对象'
                                                            }
                                                        ]
                                                    })(
                                                        <Select
                                                            disabled={
                                                                editData.disable ||
                                                                !getFieldValue('staffChecked') ||
                                                                !getFieldValue('staffConfirmEnabled')
                                                            }
                                                        >
                                                            <Select.Option value={1}>非离职员工</Select.Option>
                                                            <Select.Option value={2}>全体员工</Select.Option>
                                                        </Select>
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        ) : null}
                                        {getFieldValue('staffCheckType') === 1 ? (
                                            <Col span={8}>
                                                <Form.Item label="系统确认时间">
                                                    {getFieldDecorator('staffTriggerNext', {
                                                        initialValue: editData.staffTriggerNext || undefined,
                                                        rules: [
                                                            {
                                                                required:
                                                                    getFieldValue('staffChecked') &&
                                                                    getFieldValue('staffConfirmEnabled'),
                                                                message: '请选择系统确认时间'
                                                            }
                                                        ]
                                                    })(
                                                        <DictSelect
                                                            dictList={dictList}
                                                            dictName="StaffTriggerNextOptions"
                                                            disabled={
                                                                editData.disable ||
                                                                !getFieldValue('staffChecked') ||
                                                                !getFieldValue('staffConfirmEnabled')
                                                            }
                                                        />
                                                    )}
                                                </Form.Item>
                                            </Col>
                                        ) : null}
                                    </Row>
                                    <Row gutter={24}>
                                        <Col span={8}>
                                            <Form.Item label="允许员工反馈">
                                                {getFieldDecorator('staffFeedbackEnabled', {
                                                    initialValue: !!editData.staffFeedbackEnabled || undefined,
                                                    valuePropName: 'checked'
                                                })(
                                                    <Switch
                                                        disabled={editData.disable || !getFieldValue('staffChecked')}
                                                        onChange={onChangeStaffFeedbackEnabled}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row gutter={24}>
                                        <Col span={8}>
                                            <Form.Item label="接收反馈主管">
                                                {getFieldDecorator('staffFeedbackEmployeeCode', {
                                                    initialValue: editData?.staffFeedbackEmployeeCode || undefined,
                                                    rules: [
                                                        {
                                                            required:
                                                                getFieldValue('staffChecked') &&
                                                                getFieldValue('staffFeedbackEnabled'),
                                                            message: '请选择接收反馈主管'
                                                        }
                                                    ]
                                                })(
                                                    <SearchInput
                                                        params={{
                                                            organizationCode: selectOrganizationCode
                                                        }}
                                                        getData={async params => {
                                                            if (!params.organizationCode) {
                                                                return [];
                                                            }

                                                            const employeeResponse = await queryEmployeeList({
                                                                organizationCode: selectOrganizationCode
                                                            });
                                                            return isSuccess(employeeResponse)
                                                                ? employeeResponse.data || []
                                                                : [];
                                                        }}
                                                        selectProps={{
                                                            placeholder: '请选择',
                                                            allowClear: true,
                                                            disabled:
                                                                editData.disable ||
                                                                !getFieldValue('staffChecked') ||
                                                                !getFieldValue('staffFeedbackEnabled')
                                                        }}
                                                        fieldsName={{
                                                            value: 'employeeCode',
                                                            title: 'name'
                                                        }}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="反馈处理组织机构">
                                                {getFieldDecorator('staffFeedbackDepartmentCode', {
                                                    initialValue: editData.staffFeedbackDepartmentCode || undefined,
                                                    rules: [
                                                        {
                                                            required:
                                                                getFieldValue('staffChecked') &&
                                                                getFieldValue('staffFeedbackEnabled'),
                                                            message: '请选择反馈处理组织机构'
                                                        }
                                                    ]
                                                })(
                                                    <OrganizationSelect
                                                        place
                                                        isFunctional
                                                        disabled={
                                                            editData.disable ||
                                                            !getFieldValue('staffChecked') ||
                                                            !getFieldValue('staffFeedbackEnabled')
                                                        }
                                                        /* 审批通过的组织机构 */
                                                        extraQuery={{ auditStatus: 2 }}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row gutter={24}>
                                        <Col span={24}>
                                            <Form.Item
                                                label="薪资提示信息"
                                                labelCol={{ span: 3 }}
                                                wrapperCol={{ span: 21 }}
                                                style={{ marginLeft: '-8px' }}
                                            >
                                                {getFieldDecorator('staffTips', {
                                                    initialValue: editData.staffTips || undefined,
                                                    rules: [
                                                        {
                                                            required:
                                                                getFieldValue('staffChecked') &&
                                                                getFieldValue('staffFeedbackEnabled') &&
                                                                getFieldValue('staffTipsEnabled'),
                                                            message: '请输入薪资提示信息'
                                                        },
                                                        {
                                                            max: 50,
                                                            message: '最多可输入50个字符'
                                                        }
                                                    ]
                                                })(
                                                    <Input.TextArea
                                                        placeholder="请勿私下透露薪资信息"
                                                        disabled={
                                                            editData.disable ||
                                                            !getFieldValue('staffChecked') ||
                                                            !getFieldValue('staffFeedbackEnabled')
                                                        }
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </div>
                                <div className={styles.salaryContent}>
                                    <div className={styles.titleWrap}>
                                        <div className={styles.leftTitleWrap}>
                                            <div className={styles.title}>审批流程设置</div>
                                        </div>
                                    </div>
                                    <div className={styles.checkboxWrap}>
                                        {getFieldDecorator('workflowEnabled', {
                                            initialValue: !!editData.workflowEnabled,
                                            valuePropName: 'checked'
                                        })(
                                            <Checkbox
                                                onChange={e => {
                                                    onChangeStepList(e.target.checked, 6);
                                                }}
                                                disabled={editData.disable}
                                            >
                                                开启审批流程
                                            </Checkbox>
                                        )}
                                    </div>
                                    <Row gutter={24}>
                                        <Col span={8}>
                                            <Form.Item label="触发方式">
                                                {getFieldDecorator('workflowTriggerType', {
                                                    initialValue: editData.workflowTriggerType || 2,
                                                    rules: [
                                                        {
                                                            required: getFieldValue('workflowEnabled'),
                                                            message: '请选择触发方式'
                                                        }
                                                    ]
                                                })(
                                                    <ThingsRadioSelect
                                                        disabled={editData.disable || !getFieldValue('workflowEnabled')}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="提交审批流人员">
                                                {getFieldDecorator('workflowDutyCode', {
                                                    initialValue: makeArray(editData.workflowDutyCode, ','),
                                                    rules: [
                                                        {
                                                            required: getFieldValue('workflowEnabled'),
                                                            message: '请选择提交审批流人员'
                                                        }
                                                    ]
                                                })(
                                                    <DutySelector
                                                        disabled={editData.disable || !getFieldValue('workflowEnabled')}
                                                        multiple
                                                        showSearch
                                                        max={5}
                                                        data={dutyData}
                                                        modal
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row gutter={24}>
                                        <Col span={8}>
                                            <Form.Item label="对应审批流程名称">薪资发放申请</Form.Item>
                                        </Col>
                                    </Row>
                                </div>
                                <div className={styles.salaryContent}>
                                    <div className={styles.titleWrap}>
                                        <div className={styles.leftTitleWrap}>
                                            <div className={styles.title}>发放设置</div>
                                        </div>
                                    </div>
                                    <div className={styles.checkboxWrap}>
                                        <Checkbox disabled checked>
                                            开启发放申请
                                        </Checkbox>
                                    </div>
                                    <Row gutter={24}>
                                        <Col span={8}>
                                            <Form.Item label="触发方式">
                                                {getFieldDecorator('grantApplyTriggerType', {
                                                    initialValue: editData.grantApplyTriggerType || 2,
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请选择触发方式'
                                                        }
                                                    ]
                                                })(<ThingsRadioSelect disabled={editData.disable} />)}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="提交申请付款人员">
                                                {getFieldDecorator('grantApplyDutyCode', {
                                                    initialValue: makeArray(editData.grantApplyDutyCode, ','),
                                                    rules: [
                                                        {
                                                            required: true,
                                                            message: '请选择提交申请付款人员'
                                                        }
                                                    ]
                                                })(
                                                    <DutySelector
                                                        disabled={editData.disable}
                                                        multiple
                                                        showSearch
                                                        max={5}
                                                        data={dutyData}
                                                        modal
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <div className={styles.checkboxWrap}>
                                        {getFieldDecorator('bankPayEnabled', {
                                            initialValue: !!editData.bankPayEnabled,
                                            valuePropName: 'checked'
                                        })(
                                            <Checkbox
                                                onChange={e => {
                                                    onChangeStepList(e.target.checked, 9);
                                                }}
                                                disabled={editData.disable}
                                            >
                                                开启执行付款
                                            </Checkbox>
                                        )}
                                    </div>
                                    <Row gutter={24}>
                                        <Col span={8}>
                                            <Form.Item label="付款执行人员">
                                                {getFieldDecorator('payDutyCode', {
                                                    initialValue: makeArray(editData.payDutyCode, ','),
                                                    rules: [
                                                        {
                                                            required: getFieldValue('bankPayEnabled'),
                                                            message: '请选择付款执行人员'
                                                        }
                                                    ]
                                                })(
                                                    <DutySelector
                                                        disabled={editData.disable || !getFieldValue('bankPayEnabled')}
                                                        multiple
                                                        showSearch
                                                        max={5}
                                                        data={dutyData}
                                                        modal
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="开启银企直连">
                                                {getFieldDecorator('bankEnabled', {
                                                    initialValue: !!editData.bankEnabled || undefined,
                                                    valuePropName: 'checked'
                                                })(<Switch disabled />)}
                                            </Form.Item>
                                        </Col>
                                        <Col span={8}>
                                            <Form.Item label="选择对应的银行">
                                                {getFieldDecorator('bankName', {
                                                    initialValue: editData.bankName || undefined,
                                                    rules: [
                                                        {
                                                            required: false,
                                                            message: '请选择对应的银行'
                                                        }
                                                    ]
                                                })(
                                                    <Select
                                                        placeholder="请选择"
                                                        disabled={!getFieldValue('bankEnabled')}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </div>
                            </Form>
                            <BottomAction>
                                <AuthComponent code="finance:salary:computation:setting:sendprocess:reset">
                                    <Button onClick={() => setResetVisible(true)} disabled={!editData?.resetAble}>
                                        重置
                                    </Button>
                                </AuthComponent>
                                <AuthComponent code="finance:salary:computation:setting:sendprocess:next">
                                    <NextButton next={next} editData={editData} formValueChanged={formValueChanged}>
                                        下一步
                                    </NextButton>
                                </AuthComponent>
                                <Modal
                                    visible={resetVisible}
                                    title="重置"
                                    okText="确定"
                                    cancelText="取消"
                                    onOk={reset}
                                    onCancel={() => setResetVisible(false)}
                                    width={480}
                                    centered
                                >
                                    <div style={{ margin: '30px 20px' }}>
                                        重置后所有数据将回退到上次审批通过的结果，是否确定重置？
                                    </div>
                                </Modal>
                            </BottomAction>
                        </Spin>
                    </div>
                </TabMenuRouter>
            </TabContextMenuFilter>
        </PageHeaderWrapper>
    );
});

const SalaryTemplateForm = ({ location, history, ...otherProps }) => {
    const {
        store: { selectOrganizationCode, defaultOrganization },
        mergeTabStore
    } = useContext(TabStoreContext);
    const [formValueChanged, setFormValueChanged] = useState(false);
    const [organizationCode, setOrganizationCode] = useState();

    /* 标记是否已经初始化 */
    const initializedRef = useRef(false);

    useHistoryBlock(history);

    useEffect(() => {
        if (initializedRef.current) {
            setOrganizationCode(selectOrganizationCode);
        }
    }, [selectOrganizationCode]);

    useEffect(() => {
        const orgCode = location.query?.organizationCode;
        if (initializedRef.current && orgCode) {
            setOrganizationCode(orgCode);
        }
    }, [location]);

    useEffect(() => {
        if (!initializedRef.current) {
            const orgCode =
                selectOrganizationCode || location.query?.organizationCode || defaultOrganization?.organizationCode;

            if (orgCode) {
                initializedRef.current = orgCode;
                setOrganizationCode(orgCode);
                mergeTabStore({
                    selectOrganizationCode: orgCode,
                    countryNameCode: null
                });
            }
        }
    }, [location, selectOrganizationCode, defaultOrganization, mergeTabStore]);

    useEffect(() => {
        setFormValueChanged(false);
    }, [organizationCode]);

    const SalaryComponent = useMemo(() => {
        const formOptions = {
            name: 'addSalaryItemModal',
            onValuesChange() {
                setFormValueChanged(true);
            }
        };

        return Form.create(formOptions)(SalaryTemplate);
    }, []);

    return (
        <SalaryComponent
            selectOrganizationCode={organizationCode}
            formValueChanged={formValueChanged}
            {...otherProps}
        />
    );
};

export default withRoutePage(SalaryTemplateForm);
